package cbh.tool.inlet;

import cbh.tool.xls.FileCompleteXLS;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.stringtemplate.v4.STGroup;
import org.stringtemplate.v4.STGroupFile;

import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * Created by huxin on 2016/2/9.
 */
public class ProductXLSFileImpl implements ProduceXLSFile {

    private static final STGroup stGroup = new STGroupFile("xls.stg");

    private static final FileCompleteXLS xls = new FileCompleteXLS(stGroup);

    @Override
    public void inlet(File file, List<String> head, List...lists) throws IOException {
        xls.buildFile(file);
        xls.writeHead();
        for (int i = 0 ; i < lists.length ; i++) {
            List<Object> newList = new ArrayList<>();
            newList.add(head);
            List<Object> arr = lists[i];
            for(int j = 0 ; j < arr.size() ; j++) {
                List list = new ArrayList<>();
                new ObjectMapper().setSerializationInclusion(JsonInclude.Include.ALWAYS).convertValue(arr.get(j), Map.class).values().forEach(o -> {
                    list.add(o==null?"无":o);
                });
                newList.add(list);
            }
            xls.writeSheet("sheet"+i,newList);
        }
        xls.writeTail();
        xls.close();
    }

    @Override
    public void inletMap(File file, List<String> head, List...lists) throws IOException {
        if(!(lists[0].get(0) instanceof LinkedHashMap)){
            throw new TypeNotPresentException("is LinkedHashMap,"+lists[0].get(0).getClass().toString(),new Exception());
        }
        xls.buildFile(file);
        xls.writeHead();
        for (int i = 0 ; i < lists.length ; i++) {
            List<Object> newList = new ArrayList<>();
            newList.add(head);
            List<LinkedHashMap<Object, Object>> list = lists[i];
            for (int j = 0 ; j < list.size(); j++) {
                List<Object> arr = new ArrayList<>();
                list.get(j).values().forEach(bean -> {
                    new ObjectMapper().setSerializationInclusion(JsonInclude.Include.ALWAYS).convertValue(bean,Map.class).values().forEach(str -> arr.add(str==null?"无":str));
                });
                newList.add(arr);
            }
            xls.writeSheet("sheet"+i,newList);
        }
        xls.writeTail();
        xls.close();
    }

}

